from flask import json
from jinja2.tests import test_number
from openpyxl.styles.builtins import total
from peewee import JOIN, fn
import os,shutil
from common.public import *
from orm.model import Document, db, Customer
from view.baseview import BaseView


class DocumentView(BaseView):
    def __init__(self):
        pass

    def queryDocument(self, params):
        """根据条件取得我的客户列表，params：条件参数"""
        print(params)
        result = []
        where_condition = True
        if params["documentNumber"]:
            likestr = "%" + params["documentNumber"] + "%"

            where_condition = where_condition & (Document.document_number ** likestr)
        if params["companyname"]:
            where_condition = where_condition & (Document.customer.compname ** likestr)
        total = Document.select().join(Customer, JOIN.LEFT_OUTER, on = (Customer.id == Document.customer_id)).where(where_condition).count()
        rows = Document.select().join(Customer, JOIN.LEFT_OUTER, on = (Customer.id == Document.customer_id))\
            .where(where_condition).paginate(int(params["pageNo"]), int(params["pagesize"]))
        for row in rows: 
            data = {
                "id":row.id,
                "customerId":row.customer.id,
                "customername":row.customer.compname,
                "documentNumber":row.document_number              
             }  
            result.append(data)
        return super().resultSet(200, "取得数据成功", result, total = total)
   
    def getDirList(self,src):
        ''' 取得目标目录下的文件和目录列表 '''
        result =[]
        file_path = UPLOAD_PATH +"/" + src['curdir']
        if os.path.exists(file_path):
            files = os.listdir(file_path)
            for file in files:
                if os.path.isdir(file_path + "/"+file):
                    subfilelist = os.listdir(file_path + "/"+file)
                    result.append({"name":file,"count": str(len(subfilelist)),"type":"目录"})
                else:
                    result.append({"name":file,"type":"文件"})
        else:
            os.mkdir(file_path)
        return super().resultSet(200, "取得数据成功", result)
    
    def mkDir(self, src):
        ''' 创建目录'''
        result =[]
        file_path = UPLOAD_PATH +"/" + src['curdir'] + "/"+ src['name']
        os.mkdir(file_path)
        return super().resultSet(200, "创建目录成功", result)
    
    def rmTree(self, src):
        ''' 删除目录'''
        result =[]
        file_path = UPLOAD_PATH +"/" + src['curdir'] + "/"+ src['name']
        if os.path.exists(file_path):
            if os.path.isdir(file_path):
                shutil.rmtree(file_path)
            else:
                os.remove(file_path)
        return super().resultSet(200, "删除成功", result)
